using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using qip_history_synchronizer.Mimes;


namespace qip_history_synchronizer.Pop3
{
    class Pop3Utils
    {
        private static POP3_Client GetConnectedClient()
        {
            POP3_Client client = new POP3_Client();
            client.Connect( "pop.gmail.com", 995, true );
            client.Authenticate( "vtelushkin.icq", "", true );
            return client;
        }

        public static List<Mime> getAllMessages()
        {
            POP3_Client client = GetConnectedClient();
            POP3_MessagesInfo mInf = client.GetMessagesInfo();

            List<POP3_MessageInfo> messagesInfos = new List<POP3_MessageInfo>( mInf.Messages );

            var mimeSet = from info in messagesInfos
                          select Mime.Parse( client.GetMessage( info ) );

            List<Mime> mimeResult = mimeSet.ToList();

            return mimeResult;
        }

        public static List<Mime> getMessagesByDatePeriod( DateTime p_dtBegin, DateTime p_dtEnd )
        {
            var mimeSet = getAllMessages();

            var mimesSelected = from mimes in mimeSet
                                where mimes.MainEntity.Date>=p_dtBegin && mimes.MainEntity.Date<=p_dtEnd
                                select mimes;

            List<Mime> mimeResult = mimesSelected.ToList();

            return mimeResult;
        }

        public static List<Mime> getMessagesByDate( DateTime p_dtBegin )
        {
            return getMessagesByDatePeriod( p_dtBegin, p_dtBegin );
        }

        public static List<Mime> getMessagesBySubject( String p_sName )
        {
            var mimeSet = getAllMessages();
            var mimesSelected = from mimes in mimeSet
                                where mimes.MainEntity.Subject == p_sName
                                select mimes;

            List<Mime> mimeResult = mimesSelected.ToList();

            return mimeResult;
        }

        public static Mime getMessagesBySubjectLast( String p_sName )
        {
            var mimeSet = getMessagesBySubject( p_sName );
            var mimesSelected = from mime in mimeSet
                                orderby mime.MainEntity.Date descending 
                                select mime;

            if(mimesSelected.Count()>0)
                return mimesSelected.ToList()[0];

            return null;
        }

        public static Hashtable getMessagesWithContents()
        {
            Hashtable htResult = new Hashtable();
            List<Mime> mimes = Pop3Utils.getAllMessages();

            foreach( Mime mime in mimes )
            {
                htResult.Add( mime.MainEntity.Subject, mime.BodyText );
            }

            return htResult;
        }

    }
}